#!/bin/bash

set -x
set -e

if [[ ! -z "${JIANMU_WORKSPACE}" ]]; then
    cd ${JIANMU_WORKSPACE}
fi

if [[ ! -z "${JIANMU_REGISTRY_URL}" ]]; then
    ${JIANMU_PACKAGE_MANAGEMENT_TYPE} config set registry "${JIANMU_REGISTRY_URL}"
    ${JIANMU_PACKAGE_MANAGEMENT_TYPE} config get registry
fi

if [[ ! -z "${JIANMU_DISTURL_URL}" ]]; then
    ${JIANMU_PACKAGE_MANAGEMENT_TYPE} config set disturl "${JIANMU_DISTURL_URL}"
    ${JIANMU_PACKAGE_MANAGEMENT_TYPE} config get disturl
fi

if [[ ! -z "${JIANMU_SASS_BINARY_SITE_URL}" ]]; then
    ${JIANMU_PACKAGE_MANAGEMENT_TYPE} config set sass_binary_site "${JIANMU_SASS_BINARY_SITE_URL}"
    ${JIANMU_PACKAGE_MANAGEMENT_TYPE} config get sass_binary_site
fi

pwd

ls -a

case "${JIANMU_PACKAGE_MANAGEMENT_TYPE}" in
    npm)
        npm config set cache ${JIANMU_CACHE_PATH}
        ;;
    yarn)
        yarn config set cache-folder ${JIANMU_CACHE_PATH}
        ;;
    pnpm)
        pnpm config set store-dir ${JIANMU_CACHE_PATH}
        ;;
    *)
        echo "package_menegement_type: ${JIANMU_PACKAGE_MANAGEMENT_TYPE} {npm|yarn|pnpm}"
        exit 1
esac

${JIANMU_PACKAGE_MANAGEMENT_TYPE} install ${JIANMU_INSTALL_ARGS}

${JIANMU_PACKAGE_MANAGEMENT_TYPE} ${JIANMU_BUILD_ACTION} ${JIANMU_BUILD_ARGS}

if [[ ${JIANMU_VC_PACKAGE_DIR} =~ /$ ]];then
  package_path=${JIANMU_VC_PACKAGE_DIR}'package.json';
else
  package_path=${JIANMU_VC_PACKAGE_DIR}'/package.json';
fi

echo "{\"package_name\": $(cat ${package_path} | jq .name),\"package_version\": $(cat ${package_path} | jq .version)}" > /tmp/result.json
